#!/usr/bin/env python3
import json
import hashlib
import os
from flask import Flask, request, jsonify, abort
import requests

app = Flask(__name__)

# 节点配置
NODES = [
    "http://127.0.0.1:9527",
    "http://127.0.0.1:9528",
    "http://127.0.0.1:9529"
]

# 当前节点索引（从环境变量获取）
CURRENT_NODE_INDEX = int(os.getenv('NODE_INDEX', 0))
CURRENT_NODE_URL = NODES[CURRENT_NODE_INDEX]

# 内存存储
cache_store = {}

def get_node_index(key):
    """根据key的hash值确定存储节点"""
    hash_value = int(hashlib.md5(key.encode()).hexdigest(), 16)
    return hash_value % len(NODES)

def get_target_node_url(key):
    """获取key应该存储的节点URL"""
    node_index = get_node_index(key)
    return NODES[node_index]

@app.route('/', methods=['POST'])
def set_value():
    """写入/更新缓存"""
    try:
        data = request.get_json()
        if not data or len(data) != 1:
            return jsonify({"error": "Invalid request body"}), 400
        
        key = list(data.keys())[0]
        value = data[key]
        target_url = get_target_node_url(key)
        
        # 如果目标节点不是当前节点，转发请求
        if target_url != CURRENT_NODE_URL:
            response = requests.post(target_url, json={key: value})
            return response.content, response.status_code
        
        # 存储在当前节点
        cache_store[key] = value
        return jsonify({key: value}), 200
        
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/<key>', methods=['GET'])
def get_value(key):
    """读取缓存"""
    try:
        target_url = get_target_node_url(key)
        
        # 如果目标节点不是当前节点，转发请求
        if target_url != CURRENT_NODE_URL:
            response = requests.get(f"{target_url}/{key}")
            return response.content, response.status_code
        
        # 从当前节点获取
        if key in cache_store:
            return jsonify({key: cache_store[key]}), 200
        else:
            return '', 404
            
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/<key>', methods=['DELETE'])
def delete_value(key):
    """删除缓存"""
    try:
        target_url = get_target_node_url(key)
        
        # 如果目标节点不是当前节点，转发请求
        if target_url != CURRENT_NODE_URL:
            response = requests.delete(f"{target_url}/{key}")
            return response.content, response.status_code
        
        # 从当前节点删除
        if key in cache_store:
            del cache_store[key]
            return jsonify({"deleted": 1}), 200
        else:
            return jsonify({"deleted": 0}), 200
            
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/health', methods=['GET'])
def health_check():
    """健康检查接口"""
    return jsonify({"status": "ok", "node": CURRENT_NODE_URL}), 200

if __name__ == '__main__':
    port = 9527 + CURRENT_NODE_INDEX
    app.run(host='0.0.0.0', port=port, debug=False)
